package opencv.service.algorithms;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import opencv.service.Algorithm;

import com.googlecode.javacv.Marker;
import com.googlecode.javacv.MarkerDetector;
import com.googlecode.javacv.jna.cxcore.IplImage;

public class MarkerDetectionAlgorithm implements Algorithm {

	private MarkerDetector markerDetector;
	private Marker[] detectedMarkers;
	
	public MarkerDetectionAlgorithm() {
		
		// load library (temp) TODO - load library properly
		System.load(new File("lib/ARToolKitPlus.dll").getAbsolutePath());

		MarkerDetector.Settings settings = new MarkerDetector.Settings();
		
		int binarizationWindowMin = 5;
        int binarizationWindowMax = 63;
        double binarizationVarianceMultiplier = 1;
        double binarizationKBlackMarkers = 0.99;
        double binarizationKWhiteMarkers = 0.99;
        int subPixelWindow = 11;

		settings.setBinarizationWindowMin(binarizationWindowMin);
		settings.setBinarizationWindowMax(binarizationWindowMax);
		settings.setBinarizationVarianceMultiplier(binarizationVarianceMultiplier);
		settings.setBinarizationKBlackMarkers(binarizationKBlackMarkers);
		settings.setBinarizationKWhiteMarkers(binarizationKWhiteMarkers);
		settings.setSubPixelWindow(subPixelWindow);
		
		markerDetector = new MarkerDetector(settings);
//		markerDetector = new MarkerDetector();
		detectedMarkers = null;
	}
	
	public void onDebugImagePrepared(Image image) {
		// TODO Auto-generated method stub
	}

	public void run(IplImage img1, IplImage img2) {
		detectedMarkers = markerDetector.detect(img1, false);
		BufferedImage debug = img1.getBufferedImage();
		
		for (Marker m : detectedMarkers) {
			
			if (m.id <= 0 || m.confidence < 0) {
				continue;
			}
			
			Graphics g = debug.getGraphics();
			g.setColor(Color.red);
			g.setFont(new Font(g.getFont().getFamily(), Font.BOLD, 30));
			g.drawString(" c:"+ m.confidence, (int)m.corners[0], (int)m.corners[1]);
			g.drawString(" id:"+ m.id, (int)m.corners[0], (int)m.corners[1] + 30);
			
			for (int i=0; i < m.corners.length-1; i+=1) {
				g.fillRect((int)m.corners[i], (int)m.corners[i+1], 5, 5);
//				g.drawLine((int)m.corners[i], (int)m.corners[i+1], (int)m.corners[i-2], (int)m.corners[i-1]);
			}
			
			if (m.id == 5) {
				String pos = "[";
				for (double d : m.position) { pos += ", " + d; }
				System.out.println(pos + "]\t" + m.direction);
			}
			
		}
		
		
//		onDebugImagePrepared(markerDetector.getBinarized().getBufferedImage());
		onDebugImagePrepared(debug);
	}
	
	public Marker[] getDetectedMarkers() {
		return detectedMarkers;
	}

}
